package junweixu.jreader;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View.OnClickListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class JReaderActivity extends Activity
{
    class readFromSd extends AsyncTask<Void, String, Void>
    {
        private boolean lockFlag = false;

        @Override
        protected Void doInBackground(Void... params)
        {
            // TODO Auto-generated method stub
            File mFile = new File(BookPath);
            File[] mFiles;
            if (!mFile.exists())
            {
                mFile.mkdir();
            }
            mFiles = mFile.listFiles();
            for (int i = 0; i < mFiles.length; i++)
            {
                while (lockFlag)
                {

                }

                String mName = mFiles[i].getName();
                String exName = mName.substring(mName.lastIndexOf('.'));
                if (exName.equals(".txt") || exName.equals(".pdf"))
                {
                    lockFlag = true;
                    publishProgress(mName);
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(String... values)
        {
            // TODO Auto-generated method stub
            super.onProgressUpdate(values);
            addBookToShelf(values[0]);
            bookShelfAdapter.notifyDataSetChanged();
            lockFlag = false;
        }
    }

    private void addBookToShelf(String mName)
    {
        bookCount++;
        int lineNum = (bookCount - 1) / 3;
        int linePos = (bookCount - 1) % 3;
        if (lineNum <= 3)
        {
            Map<String, Object> mDataMap = bookShelfListViewList.get(lineNum);
            switch (linePos)
            {
            case 0:
                mDataMap.remove("leftText");
                mDataMap.put("leftText", mName);
                break;
            case 1:

                mDataMap.remove("midText");
                mDataMap.put("midText", mName);
                break;
            case 2:

                mDataMap.remove("rightText");
                mDataMap.put("rightText", mName);
                break;
            }
            bookShelfListViewList.set(lineNum, mDataMap);
        } else
        {
            Map<String, Object> mDataMap = new HashMap<String, Object>();
            mDataMap.put("leftImg", R.drawable.cover_txt);
            mDataMap.put("midImg", R.drawable.cover_txt);
            mDataMap.put("rightImg", R.drawable.cover_txt);
            mDataMap.put("leftText", mName);
            mDataMap.put("midText", "null");
            mDataMap.put("rightText", "null");
            bookShelfListViewList.add(mDataMap);
        }
    }

    private static final String BookPath = "/sdcard/JreaderBooks";

    class MySimpleAdapter extends SimpleAdapter
    {

        public MySimpleAdapter(Context context,
                List<? extends Map<String, ?>> data, int resource,
                String[] from, int[] to)
        {
            super(context, data, resource, from, to);
            // TODO Auto-generated constructor stub
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            convertView = super.getView(position, convertView, parent);
            ImageView mLeftImg = (ImageView) convertView
                    .findViewById(R.id.leftBookImg);
            ImageView mMidImg = (ImageView) convertView
                    .findViewById(R.id.midBookImg);
            ImageView mRightImg = (ImageView) convertView
                    .findViewById(R.id.rightBookImg);
            TextView mLeftText = (TextView) convertView
                    .findViewById(R.id.leftBookTextView);
            TextView mMidText = (TextView) convertView
                    .findViewById(R.id.midBookTextView);
            TextView mRightText = (TextView) convertView
                    .findViewById(R.id.rightBookTextView);
            mLeftImg.setOnClickListener(imgClickListener);
            mMidImg.setOnClickListener(imgClickListener);
            mRightImg.setOnClickListener(imgClickListener);
            mLeftImg.setVisibility(View.GONE);
            mMidImg.setVisibility(View.GONE);
            mRightImg.setVisibility(View.GONE);
            mLeftText.setVisibility(View.GONE);
            mMidText.setVisibility(View.GONE);
            mRightText.setVisibility(View.GONE);
            if (position < bookCount / 3)
            {
                mLeftImg.setVisibility(View.VISIBLE);
                mMidImg.setVisibility(View.VISIBLE);
                mRightImg.setVisibility(View.VISIBLE);
                mLeftText.setVisibility(View.VISIBLE);
                mMidText.setVisibility(View.VISIBLE);
                mRightText.setVisibility(View.VISIBLE);
            } else if (0 == bookCount)
            {
            } else if ((bookCount - 1) / 3 == position)
            {
                switch (bookCount % 3)
                {
                case 0:
                    mRightImg.setVisibility(View.VISIBLE);
                    mRightText.setVisibility(View.VISIBLE);
                case 2:
                    mMidImg.setVisibility(View.VISIBLE);
                    mMidText.setVisibility(View.VISIBLE);
                case 1:
                    mLeftImg.setVisibility(View.VISIBLE);
                    mLeftText.setVisibility(View.VISIBLE);
                    break;
                }
            }
            return convertView;
        }
    }

    private int bookCount = 0;
    private List<Map<String, Object>> bookShelfListViewList = new ArrayList<Map<String, Object>>();
    private MySimpleAdapter bookShelfAdapter;
    private ListView bookShelfListView;
    private long exitTime = 0;
    private OnClickListener imgClickListener = new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub

            String mName = "";
            switch (v.getId())
            {
            case R.id.leftBookImg:
                mName = bookShelfListViewList
                        .get(bookShelfListView.getPositionForView(v))
                        .get("leftText").toString();
                break;
            case R.id.midBookImg:
                mName = bookShelfListViewList
                        .get(bookShelfListView.getPositionForView(v))
                        .get("midText").toString();
                break;
            case R.id.rightBookImg:
                mName = bookShelfListViewList
                        .get(bookShelfListView.getPositionForView(v))
                        .get("rightText").toString();
                break;
            default:
                break;
            }
            Intent intent = new Intent();
            String exName = mName.substring(mName.lastIndexOf('.'));
            if (exName.equals(".txt"))
                intent.setClass(JReaderActivity.this, MyReaderActivity.class);
            else if (exName.equals(".pdf"))
                intent.setClass(JReaderActivity.this, PdfReaderActivity.class);
            intent.putExtra("path", BookPath + '/' + mName);
            startActivity(intent);
        }
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.book_shelf);
        initBookShelfListViewList();
        bookShelfListView = (ListView) findViewById(R.id.bookShelfListView);
        bookShelfAdapter = new MySimpleAdapter(this, bookShelfListViewList,
                R.layout.book_shelf_layer, new String[] { "leftImg", "midImg",
                        "rightImg", "leftText", "midText", "rightText" },
                new int[] { R.id.leftBookImg, R.id.midBookImg,
                        R.id.rightBookImg, R.id.leftBookTextView,
                        R.id.midBookTextView, R.id.rightBookTextView });
        bookShelfListView.setAdapter(bookShelfAdapter);
        new readFromSd().execute();
    }

    private void initBookShelfListViewList()
    {
        for (int i = 0; i < 3; i++)
        {
            Map<String, Object> mDataMap = new HashMap<String, Object>();
            mDataMap.put("leftImg", R.drawable.cover_txt);
            mDataMap.put("midImg", R.drawable.cover_txt);
            mDataMap.put("rightImg", R.drawable.cover_txt);
            mDataMap.put("leftText", "null");
            mDataMap.put("midText", "null");
            mDataMap.put("rightText", "null");
            bookShelfListViewList.add(mDataMap);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            if (event.getRepeatCount() == 0)
            {
                if ((System.currentTimeMillis() - exitTime) > 2000)
                {
                    Toast.makeText(this, "再按一次返回键退出程序", Toast.LENGTH_SHORT)
                            .show();
                    exitTime = System.currentTimeMillis();
                } else
                {
                    finish();
                    System.exit(0);
                }
                return true;
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}